package org.example.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * WebClient配置
 */
@Configuration
@RequiredArgsConstructor
public class WebClientConfig {

    private final PanSouProperties panSouProperties;

    @Bean
    public WebClient webClient() {
        // 连接池配置
        ConnectionProvider connectionProvider = ConnectionProvider.builder("pansou-http-pool")
                .maxConnections(panSouProperties.getHttp().getMaxConnections())
                .maxIdleTime(panSouProperties.getHttp().getIdleTimeout())
                .maxLifeTime(Duration.ofMinutes(30))
                .pendingAcquireTimeout(Duration.ofSeconds(60))
                .evictInBackground(Duration.ofSeconds(120))
                .build();

        // HTTP客户端配置
        HttpClient httpClient = HttpClient.create(connectionProvider)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    (int) panSouProperties.getHttp().getReadTimeout().toMillis())
                .doOnConnected(conn -> conn
                    .addHandlerLast(new ReadTimeoutHandler(
                        panSouProperties.getHttp().getReadTimeout().toSeconds(), TimeUnit.SECONDS))
                    .addHandlerLast(new WriteTimeoutHandler(
                        panSouProperties.getHttp().getWriteTimeout().toSeconds(), TimeUnit.SECONDS))
                );

        // 如果启用代理
        if (panSouProperties.getProxy().isEnabled() && panSouProperties.getProxy().getUrl() != null) {
            // 这里可以添加代理配置
            // httpClient = httpClient.proxy(proxy -> proxy.type(ProxyProvider.Proxy.SOCKS5)...);
        }

        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }

    @Bean("fastWebClient")
    public WebClient fastWebClient() {
        // 快速响应的WebClient（用于异步插件的快速响应）
        ConnectionProvider fastConnectionProvider = ConnectionProvider.builder("pansou-fast-http-pool")
                .maxConnections(panSouProperties.getHttp().getMaxConnectionsPerHost())
                .maxIdleTime(Duration.ofMinutes(2))
                .maxLifeTime(Duration.ofMinutes(5))
                .pendingAcquireTimeout(Duration.ofSeconds(10))
                .evictInBackground(Duration.ofSeconds(30))
                .build();

        HttpClient fastHttpClient = HttpClient.create(fastConnectionProvider)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    (int) panSouProperties.getAsync().getResponseTimeout().toMillis())
                .doOnConnected(conn -> conn
                    .addHandlerLast(new ReadTimeoutHandler(
                        panSouProperties.getAsync().getResponseTimeout().toSeconds(), TimeUnit.SECONDS))
                    .addHandlerLast(new WriteTimeoutHandler(
                        panSouProperties.getAsync().getResponseTimeout().toSeconds(), TimeUnit.SECONDS))
                );

        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(fastHttpClient))
                .build();
    }
}